import Vue from 'vue'
import Router from 'vue-router'
import Layout from '@/layout'
Vue.use(Router)

// 一开始就挂载的基本路由
export const basicRoutes = [
  {
    path: '/redirect',
    component: Layout,
    hidden: true,
    children: [
      {
        path: '/redirect/:path(.*)',
        component: () => import('@/views/error/redirect'),
      },
    ],
  },
  {
    path: '/404',
    hidden: true,
    component: () => import('@/views/error/404'),
  },
]

// js加载router文件夹里的modules路由
function loadRouterModules() {
  const modulesFiles = require.context('./modules', true, /\.js$/)

  const routeModules = modulesFiles.keys().reduce((modules, modulePath) => {
    const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
    const value = modulesFiles(modulePath)
    modules[moduleName] = value.default
    return modules
  }, {})
  const rootRouteList = Object.values(routeModules)

  rootRouteList.sort((a, b) => (a.order || 0) - (b.order || 0))

  return [
    ...rootRouteList,
    { path: '*', redirect: '/404', hidden: true }, // 没找到页面的匹配路由放在最后
  ]
}

// 创建路由的函数
function createRouter() {
  const baseUrl = process.env.BASE_URL || '/'
  const routerMode = process.env.VUE_APP_ROUTER_MODE || 'hash'
  const router = new Router({
    base: baseUrl,
    mode: routerMode,
    scrollBehavior: () => ({ y: 0 }),
    routes: basicRoutes,
  })

  return router
}

// 新建路由
const router = createRouter()

// 导出动态路由
export const asyncRoutes = loadRouterModules()

// 导出路由重置方法
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher
}

// 导出路由实例
export default router
